#!/usr/bin/env python

import gtk
import webkit
import json
import os

JAVASCRIPT = """
var _callbacks = {};
function trigger (message, data) {
    if (typeof(_callbacks[message]) !== "undefined") {
        var i = 0;
        while (i < _callbacks[message].length) {
            _callbacks[message][i](data);
            i += 1;
        }
    }
}
function send (message, data) {
    document.title = ":";
    document.title = message + ":" + JSON.stringify(data);
}
function listen (message, callback) {
    if (typeof(_callbacks[message]) === "undefined") {
        _callbacks[message] = [callback];
    } else {
        _callbacks[message].push(callback);
    }
}
"""

class HTMLFrame(gtk.ScrolledWindow):
    def __init__(self):
        super(HTMLFrame, self).__init__()
        self._callbacks = {}
        self.show()
        self.webview = webkit.WebView()
        self.webview.show()
        self.add(self.webview)
        self.webview.connect('title-changed', self.on_title_changed)

    def open_url(self, url):
        self.webview.open(url);
        self.webview.execute_script(JAVASCRIPT)

    def open_path(self, path):
        self.open_url("file://" + os.path.abspath(path))
        self.webview.execute_script(JAVASCRIPT)

    def send(self, message, data):
        self.webview.execute_script(
            "trigger(%s, %s);" % (
                json.dumps(message),
                json.dumps(data)
            )
        )

    def listen(self, message, callback):
        if self._callbacks.has_key(message):
            self._callbacks[message].append(callback)
        else:
            self._callbacks[message] = [callback]

    def trigger(self, message, data, *a):
        if self._callbacks.has_key(message):
            for callback in self._callbacks[message]:
                callback(data)

    def on_title_changed(self, w, f, title):
        t = title.split(":")
        message = t[0]
        if not message == "":
            data = json.loads(":".join(t[1:]))
            self.trigger(message, data)

 

def fm_news(data):
    print "foomovies News here"

def fm_feats(data):
    print "foomovies Feats here"


if __name__ == "__main__":
    
    import subprocess
    import signal
    
    pipe = subprocess.Popen(['python', "-m", "SimpleHTTPServer", "8015"])
    
    window = gtk.Window()
    window.resize(950, 600)
    window.set_title("fooMovies")
    frame = HTMLFrame()
    
    frame.open_path("themes/default/index.html")    
    
    def reply(data):
        frame.send("alert", " ".join(data))
    
    frame.listen("fm_news", fm_news)
    frame.listen("fm_feats", fm_feats)    
    
    window.add(frame)
    window.show_all()
    window.connect("destroy", gtk.main_quit)
    
    
    
    gtk.main()
	


"""    
#frame.open_path("page.html")
#frame.open_path("mediaplayer/readme.html")
#frame.open_path("flowplayer/example/index2.html")
#frame.open_path("flowplayer/example/index2.html")

#JWPlayer
frame.open_url("http://localhost:8015/players/jwplayer/index.html")


#Flowplayer
#frame.open_url("http://localhost:8015/players/flowplayer/index.html")

#Html5
#frame.open_url("http://localhost:8015/players/html5/index.html")    

#Flare
#frame.open_url("http://localhost:8015/players/flare/index.html")        

#Cuevana
#frame.open_url("http://localhost:8015/players/cuevana/index.html")        

#Video-JS
#frame.open_url("http://localhost:8015/players/video-js2/index.html")
"""



"""
##python -m SimpleHTTPServer 8015    
import SimpleHTTPServer
import SocketServer

PORT = 8015

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT

httpd.serve_forever()    
"""
